﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace XrmLibrary.MsCrm4Adapter.Extensions
{
    public static class LinkEntityExtensions
    {
        public static Microsoft.Crm.Sdk.Query.LinkEntity ToCrm4LinkEntity(this Microsoft.Xrm.Sdk.Query.LinkEntity crm2011LinkEntity)
        {
            Microsoft.Crm.Sdk.Query.LinkEntity crm4LinkEntity =
                new Microsoft.Crm.Sdk.Query.LinkEntity()
                {
                    LinkFromAttributeName = crm2011LinkEntity.LinkFromAttributeName,
                    LinkFromEntityName = crm2011LinkEntity.LinkFromEntityName,
                    LinkToEntityName = crm2011LinkEntity.LinkToEntityName,
                    LinkToAttributeName = crm2011LinkEntity.LinkToAttributeName,
                    JoinOperator = crm2011LinkEntity.JoinOperator.ToCrm4JoinOperator(),
                    LinkCriteria = crm2011LinkEntity.LinkCriteria.ToCrm4FilterExpression()
                };

            // Set child Link Entities (if any).
            foreach (Microsoft.Xrm.Sdk.Query.LinkEntity linkEntity in crm2011LinkEntity.LinkEntities)
            {
                crm4LinkEntity.LinkEntities.Add(linkEntity.ToCrm4LinkEntity());
            }

            return crm4LinkEntity;
        }

        public static Microsoft.Xrm.Sdk.Query.LinkEntity ToCrm2011LinkEntity(this Microsoft.Crm.Sdk.Query.LinkEntity crm4LinkEntity)
        {
            Microsoft.Xrm.Sdk.Query.LinkEntity crm2011LinkEntity =
                new Microsoft.Xrm.Sdk.Query.LinkEntity()
                {
                    LinkFromAttributeName = crm4LinkEntity.LinkFromAttributeName,
                    LinkFromEntityName = crm4LinkEntity.LinkFromEntityName,
                    LinkToEntityName = crm4LinkEntity.LinkToEntityName,
                    LinkToAttributeName = crm4LinkEntity.LinkToAttributeName,
                    JoinOperator = crm4LinkEntity.JoinOperator.ToCrm2011JoinOperator(),
                    LinkCriteria = crm4LinkEntity.LinkCriteria.ToCrm2011FilterExpression()
                };

            // Set Link Entity (if any).
            crm2011LinkEntity.LinkEntities.AddRange(crm4LinkEntity.LinkEntities.ToCrm2011LinkEntityCollection());
            
            return crm2011LinkEntity;
        }

        public static IEnumerable<Microsoft.Xrm.Sdk.Query.LinkEntity> ToCrm2011LinkEntityCollection(this ArrayList crm4LinkEntity)
        {
            foreach (Microsoft.Crm.Sdk.Query.LinkEntity linkEntity in crm4LinkEntity)
            {
                yield return linkEntity.ToCrm2011LinkEntity();
            }
        }
    }
}
